<template>
  <div class="dc">
    <div class="history-curve">
      <div class="info">
        <div class="title">地测</div>
      </div>

      <div class="content">
        <!-- 右边图表区 -->
        <BEchart ref="bEchartRef" class="charts" :options="option"></BEchart>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted, createVNode, render, shallowRef } from 'vue'
import BEchart from '@/components/b-echart/index.vue'
import { useAuthStore } from '@/store/auth'
import { storeToRefs } from 'pinia'
import axios from 'axios'
import { useFocusObject } from '@/utils/useFocusObject'
import { useActiveObject } from '@/store/activeObject'
import { gsap } from 'gsap'
import { useViewportStore } from '@/store/viewport'
import { useAddTools } from '@/utils/useAddTools'
import { CSS2DObject } from 'three/examples/jsm/Addons.js'
import BRoad from '@/components/b-road.vue'
interface ChartDataItem {
  dateMinute: string
  cdValue: number
  formatter: string
  cdState?: string
  cdStateName?: string
  showValue?: string
  unitCode?: string
  cdLocation?: string
}

interface ChartData {
  cdCode: string
  cdLocation: string
  data: ChartDataItem[]
  sensorType?: string
  maxValue?: number
  minValue?: number
  averageValue?: number
  unitCode?: string
  bjIndexs?: Array<[number, number]>
  bxIndexs?: Array<[number, number]>
}

interface SearchData {
  timeRange: [string, string]
  checkedCdCode: string[]
}

interface AreaLocation {
  cdCode: string
  areaLocation: string
}

const loading = ref(false)
const sensorList = ref<AreaLocation[]>([])

const searchData = ref<SearchData>({
  timeRange: ['', ''],
  checkedCdCode: []
})

const bEchartRef = ref()
const option = ref({
  color: [
    '#FC9E40',
    '#C43CC4',
    '#ffff00',
    '#ffa500',
    '#0000FF',
    '#9400d3',
    '#9f79ee',
    '#696969',
    '#ff00ff',
    '#bdb76b',
    '#cd5c5c',
    '#006400',
    '#00bfff',
    '#66cd00',
    '#8b8989',
    '#ff1493'
  ],
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      snap: true,
      lineStyle: {
        width: 3,
        type: 'solid'
      }
    },
    formatter: (params: any) => {
      let result = ''
      if (Array.isArray(params)) {
        params.forEach((item: any, index: number) => {
          if (index === 0) {
            result += item.data.dateMinute + '<br>'
          }
          result += item.marker + item.data.formatter + '<br>'
        })
      }
      return result
    }
  },
  legend: {
    top: '0',
    type: 'plain',
    left: 'center',
    data: [],
    textStyle: {
      color: '#00FFA7',
      fontSize: 12
    }
  },
  grid: {
    top: '35',
    left: '30',
    right: '30',
    bottom: '40'
  },
  xAxis: {
    type: 'category',
    axisLine: {
      show: true,
      lineStyle: {
        color: '#00FFA7'
      }
    }
  },
  yAxis: [
    {
      type: 'value',
      name: '日进尺',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#00FFA7'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#0f5741'
        }
      }
    },
    {
      type: 'value',
      name: '状态',
      axisLabel: {
        show: true,
        formatter: (value) => {
          if (value == 0) return '无'
          else if (value == 1) return '有'
        },
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#00FFA7'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#0f5741'
        }
      }
    }
  ],
  series: []
})

const chartDatas = ref()
const BASE_URL = import.meta.env.BASE_URL
const getHisGraphFun = async () => {
  loading.value = true
  try {
    const { data: dc } = await axios.get(BASE_URL + 'dcJson.json')
    chartDatas.value = dc
    showEChartData(dc)
  } finally {
    loading.value = false
  }
}

const isNotNull = (value: any): boolean => {
  return value !== null && value !== undefined
}

const getString = (value: any): string => {
  return value?.toString() || ''
}

function showEChartData(chartDatas: ChartData[]) {
  const formatter = (data): string => {
    let s = data.cdLocation || ''

    if (isNotNull(data.cdValue)) {
      s += ' ' + data.showValue
    }

    // 不正常
    if (getString(data.cdState) !== '0') {
      s += ' ' + getString(data.cdStateName)
    }
    return s
  }

  for (let i = 0; i < chartDatas.length; i++) {
    const chartData = chartDatas[i]
    const { data, cdLocation, bjIndexs, sensorType } = chartData
    option.value.legend.data.push({
      name: cdLocation
    })

    let step: boolean | 'start' = ''
      // 开关的特殊处理
    console.log(sensorType)
    if (sensorType && sensorType.substr(0, 1) !== '0') {
        step = 'start'
    }

    // 增加tag和初始化series
    option.value.series.push({
      type: 'line',
      name: cdLocation,
      data: [],
      color: cdLocation === '人数曲线' ? '#69f' : '',
      symbol: 'none',
      lineStyle: {
        width: 2
      },
      yAxisIndex: i,
      step
    })

    // 标校 报警
    if (bjIndexs && bjIndexs.length) {
      if (bjIndexs && bjIndexs.length) {
        const bjValues = bjIndexs.map((scope: [number, number]) => {
          const arr = [data[scope].dateMinute]
          if (scope[1] !== undefined) {
            arr.push(data[scope].dateMinute)
          } else {
            arr.push(data[scope].dateMinute)
          }
          return arr
        })
        option.value.series[i].markArea = {
          itemStyle: {
            color: option.value.color[i],
            opacity: 0.2
          },
          data: bjValues.map((item) => {
            return [
              {
                name: '报警',
                label: {
                  color: option.value.color[i]
                },
                xAxis: item[0]
              },
              {
                xAxis: item[1]
              }
            ]
          })
        }
      }
    }

    for (let x = 0; x < data.length; x++) {
      const obj = data[x]
      option.value.series[i].data.push({
        value: [obj.dateMinute, obj.cdValue],
        dateMinute: obj.dateMinute,
        formatter: formatter(obj)
      })
    }
  }
}

const authStore = useAuthStore()
const { globalParams } = storeToRefs(authStore)
const activeObjectStore = useActiveObject()
const { activeShallowRef } = storeToRefs(activeObjectStore)
const { focusObject } = useFocusObject()
const viewportStore = useViewportStore()
const { publicGroup } = storeToRefs(viewportStore)
const timeline = gsap.timeline()
const i = ref({ t: 0 })
const label = shallowRef()
onMounted(async () => {
  setTimeout(() => {
    focusObject(activeShallowRef.value)
    label.value = ctreateLabel()
    publicGroup.value.add(label.value)
    oldNode = activeShallowRef.value
    timeline.to(i, {
      t: 8,
      duration: 16,
      ease: 'linear',
      onUpdate: () => {
        const progress = timeline.progress()
        const chartIndex = Math.ceil(8 * progress)
        changTooltip(bEchartRef.value.chartInstance, chartIndex)
        progressToRoad(progress)
      },
      onComplete: () => {
        console.log(activeShallowRef.value)
      }
    })
    timeline.play()
  }, 1000)

  sensorList.value.push({
    areaLocation: '1213瓦斯鉴定巷1掘进工作面日进尺',
    cdCode: 'dc_1213'
  })
  authStore.setSceneTypeList(sensorList.value)

  searchData.value.timeRange = [globalParams.value.startTime, globalParams.value.endTime]
  searchData.value.checkedCdCode = [globalParams.value.cdCode, 'dc_1213']
  await getHisGraphFun()
  changTooltip(bEchartRef.value.chartInstance, 0)

  watch(
    searchData.value,
    () => {
      getHisGraphFun()
    },
    {
      deep: true
    }
  )
})

function changTooltip(chartInstance: echarts.ECharts, index: number) {
  chartInstance.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: index
  })
}

// 巷道动画
let oldProgress = 0
let oldNode
const { addRoadway } = useAddTools()
function progressToRoad(progress) {
  // 计算当前需要显示的点数
  const points = oldNode.geometry.parameters.path.getPoints(100)
  const visiblePoints = Math.ceil(progress * points.length)
  if (oldProgress === visiblePoints) return
  oldProgress = visiblePoints
  // 创建新的曲线
  const partialPoints = points.slice(0, visiblePoints)
  // const partialCurve = new CatmullRomCurve3(partialPoints);
  // 创建新的几何体
  addRoadway(
    'edit',
    {
      name: oldNode.name,
      coordinates: partialPoints,
      closed: false
    },
    false
  )
  label.value.position.copy(partialPoints[visiblePoints - 1])
  currentRoadInfo.value = chartDatas.value[0].data[Math.ceil(progress * chartDatas.value[0].data.length)]
}
const currentRoadInfo = ref({})
function ctreateLabel() {
  const container = document.createElement('div')
  const vm = createVNode(
    BRoad,
    {
      info: currentRoadInfo
    },
    null
  )
  render(vm, container)
  const label = new CSS2DObject(container.firstElementChild as Node)
  label.Vnode = vm
  return label
}

onUnmounted(() => {
  timeline.kill()
  label.value.removeFromParent()
  progressToRoad(1)
})
</script>

<style lang="scss" scoped>
.dc {
  height: 300px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  background: var(--bg-color-page);
  padding: 8px;
  overflow: hidden;

  .history-curve {
    display: flex;
    flex-direction: column;
    flex: 1;
    height: 100%;
    overflow: hidden;
    gap: 8px;

    .info {
      display: flex;
      align-items: center;
      gap: 16px;
      background: var(--bg-color-page);
      padding: 8px;

      .title {
        min-width: 286px;
        line-height: 35px;
        padding-left: 14px;
        padding-right: 100px;
        height: 35px;
        background-image: url(/src/assets/images/bdialog/title-bg.png);
        background-size: 100% 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-right: 16px;
      }

      .info-item {
        display: flex;
        align-items: center;

        :deep(.el-switch__action) {
          background-color: #fff;
        }
      }

      .sensor-type-checkbox {
        height: 240px;
        overflow-y: auto;
        flex-direction: column;
      }

      .sensor-input {
        width: 180px;
        margin: 0 8px 0 4px;
      }

      .time-picker {
        flex: 1;
      }
    }

    .content {
      display: flex;
      flex: 1;
      overflow: hidden;
      padding: 8px;
      background: var(--bg-color-page);

      .left {
        margin-top: 8px;
        height: calc(100% - 8px);
        flex-shrink: 0;
        overflow-y: auto;
        padding-right: 16px;

        .my-checkbox {
          flex-direction: column;

          .el-checkbox {
            margin-right: 0;
            color: var(--text-color-placeholder);
          }
        }
      }

      .charts {
        flex: 1;
        overflow: hidden;
      }
    }
  }
}
</style>
